<template>
    <a-spin :spinning="loading" class="importUser">
        <div slot="indicator">
            <a-steps :current="stepCurrent" size="small" :status="stepStatus" class="importUser-step">
                <a-step :title="item" v-for="(item, key) in ['解析表格', '检验数据', '上传数据']" :key="key">
                    <a-icon slot="icon" type="loading" v-if="key=== stepCurrent && stepStatus === 'finish'" />
                </a-step>
            </a-steps>
        </div>
    <page-layout-content>
        <h1 class="importUser-title">批量导入用户</h1>
        <template v-if="pageStatus === 'upload'">
            <div class="importUser-row">
                <h3>①准备数据</h3>
                <p>导入的用户数量需小于100，所有允许导入的字段请参考模板；若导入字段不符合规则，将导致导入失败。</p>
                <ul>
                    <li v-for="(item, index) in [
                   '红色字段为必填字段，黑色字段为选填字段；',
                    '“性别”请填写：男、女；',
                    '出生日期格式为：YYYY/MM/DD；',
                    '“所属机构”填写的内容请与平台保持一致。'
                ]" :key="index">{{item}}</li>
                </ul>
                <a-button type="link" @click="toExport">
                    <a-icon type="vertical-align-bottom" />下载导入模板
                </a-button>
            </div>
            <div class="importUser-row">
                <h3>②上传数据文件</h3>
                <p>目前支持的文件类型为*.xls, *.xlsx。</p>
                <userUpload ref="userUpload"/>
            </div>
            <div class="importUser-btn">
                <a-space>
                    <a-button type="primary" @click="parsingXlsx">
                        下一步
                    </a-button>
                    <a-button @click="goBack">取消</a-button>
                </a-space>
            </div>
        </template>
        <template v-if="pageStatus === 'error'">
            <div class="error-page">
                <a-alert type="error" show-icon >
                    <span slot="message">
                        当前表格中有<span style="color: red">{{xlsDataErrNum}}</span>条错误，请修改完成后重新上传。
                    </span>
                </a-alert>
                <errTable :data="xlsData"/>
                <a-button type="primary"
                          @click="uploadAgain"
                          style="display:block;margin: auto;width: 139px;"
                >
                    重新上传
                </a-button>
            </div>
        </template>
        <template v-if="pageStatus === 'success'">
            <a-result
                    status="success"
                    title="上传成功"
            >
                <template #extra>
                    <a-button key="console"
                              style="width: 139px;"
                              @click="goBack"
                              type="primary">
                        返回
                    </a-button>
                    <a-button key="buy"
                              style="width: 139px;"
                              @click="uploadAgain">
                        再次上传
                    </a-button>
                </template>
            </a-result>
        </template>
    </page-layout-content>
    </a-spin>
</template>

<script>
    import moment from 'moment';
    import userUpload from './upload';
    import errTable from "./errTable";
    import {isPhone} from "@/utils/util";
    import pageLayoutContent from "@/components/pageLayoutContent";

    export default {
        name: "index",
        components: {
            pageLayoutContent,
            userUpload,
            errTable
        },
        data() {
          return {
              loading: false,
              xlsData: [],
              xlsDataErrNum: 0,
              stepCurrent: 0,
              stepStatus: 'finish',
              pageStatus: 'upload', // upload error success
          }
        },
        methods: {
            goBack() {
                this.$router.push('/UserManagement/dataMonitoring')
            },
            toExport(){
                // 批量导入用户模版.xlsx
                window.open('/批量导入用户模版.xlsx');
            },
            uploadAgain() {
                this.xlsDataErrNum = 0;
                this.pageStatus = 'upload';
                this.stepStatus='finish'
            },
            parsingXlsx() {
                let files = this.$refs['userUpload'].fileList
                if (files.length > 0) {
                    this.xlsData = [];
                    this.stepCurrent = 0;
                    this.loading = true;
                    files.forEach((value, key) => {
                        this.parsingFile(value, files.length - key  === 1);
                    })
                } else {
                    this.$message.warning('请上传文件');
                }
            },
            parsingFile(file, loading) {
                let _this = this;
                var rABS = false; //是否将文件读取为二进制字符串
                var f = file;
                var reader = new FileReader();
                //if (!FileReader.prototype.readAsBinaryString) {
                FileReader.prototype.readAsBinaryString = function(f) {
                    var binary = "";
                    var rABS = false; //是否将文件读取为二进制字符串
                    // var pt = this;
                    var wb; //读取完成的数据
                    var outdata;
                    var reader = new FileReader();
                    reader.onload = function() {
                        var bytes = new Uint8Array(reader.result);
                        var length = bytes.byteLength;
                        for (var i = 0; i < length; i++) {
                            binary += String.fromCharCode(bytes[i]);
                        }
                        var XLSX = require("xlsx");

                        if (rABS) {
                            wb = XLSX.read(btoa(window.fixdata(binary)), {
                                //手动转化
                                type: "base64"
                            });
                        } else {
                            wb = XLSX.read(binary, {
                                type: "binary"
                            });
                        }
                        outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
                        let requestData = [];
                        let headArr = ["*姓名","*性别","*电话","*出生日期","设备IMEI","*所属机构","姓名","电话","姓名","电话","姓名","电话","姓名","电话","姓名","电话"]
                        if (JSON.stringify(headArr.sort()) !== JSON.stringify(Object.values(outdata[0]).sort())) {
                            setTimeout(() => {
                                _this.stepStatus = 'error';
                                _this.loading = false;
                                _this.stepStatus='finish';
                                _this.$message.error('请使用导入模版格式上传！');
                            }, 500)
                            return;
                        }
                        for (let i = 1; i < outdata.length; i++) {
                            let item = outdata[i];
                            requestData.push({
                                name: item['基本信息'],
                                gender: item['__EMPTY'],
                                phone: item['__EMPTY_1'],
                                imei: item['__EMPTY_3'],
                                birth: item['__EMPTY_2'],
                                institutions: item['__EMPTY_4'],
                                contact: [
                                    {name: item['紧急联系人'], phone: item['__EMPTY_5']},
                                    {name: item['__EMPTY_6'], phone: item['__EMPTY_7']},
                                    {name: item['__EMPTY_8'], phone: item['__EMPTY_9']},
                                    {name: item['__EMPTY_10'], phone: item['__EMPTY_11']},
                                    {name: item['__EMPTY_12'], phone: item['__EMPTY_13']},
                                ]
                            })
                        }
                        _this.xlsData = _this.xlsData.concat(requestData)
                        if (loading) {
                            setTimeout(() => {
                                _this.february();
                            }, 750)
                        }
                    };
                    reader.readAsArrayBuffer(f);
                };
                if (rABS) {
                    reader.readAsArrayBuffer(f);
                } else {
                    reader.readAsBinaryString(f);
                }
            },
            february() {
                this.stepCurrent = 1;
                this.xlsData = this.xlsData.map(value => {
                    let err = [];
                    // 判断用户名
                    if (value.name === '') {err.push('姓名不能为空')}
                    if (value.gender === ''){err.push('性别不能为空')}
                    if (value.gender !== '男' && value.gender !== '女'){err.push('性别不能为空')}
                    if (!isPhone(value.phone)){err.push('手机号格式错误')}
                    if (value.birth === '') {err.push('出生日期不能为空')}
                    if (value.birth) {
                        value.birth = moment(value.birth).format('YYYY/MM/DD')
                    }
                    let concatErr = value.contact.some(({name, phone}) => {
                        if (name && phone && isPhone(phone)) {
                            return true;
                        } else{
                            return false;
                        }
                    })
                    if (!concatErr) {
                        err.push('紧急联系人数据错误, 请检查')
                    }
                    if(err.length) {
                        this.xlsDataErrNum++;
                    }
                    return {
                        ...value,
                        err
                    }
                })
                setTimeout(() => {
                    if (this.xlsDataErrNum) {
                        this.stepStatus = 'error';
                        setTimeout(() => {
                            this.pageStatus = 'error';
                            this.loading = false;
                        }, 500)
                    } else {
                        this.stepCurrent = 2;
                        setTimeout(() => {
                            this.pageStatus = 'success';
                            this.loading = false;
                        }, 500)
                    }
                }, 750)
            }
        }
    }
</script>

<style lang="less">
    .importUser{
         div > .ant-spin{
            bottom: 0!important;
            margin: auto!important;
        }
        .ant-steps-item-container{
            width: 100px;
        }
        .ant-steps-small.ant-steps-horizontal:not(.ant-steps-label-vertical) .ant-steps-item:last-child{
            width: 0px;
        }
        .ant-spin-dot{
            width: 60%!important;
            left: 0!important;
            right: 0!important;
            bottom: 0!important;
            top: 0!important;
            margin: auto!important;
        }
        .ant-steps{
            justify-content: center;
        }
        .ant-steps-item{
            flex: auto;
        }
    }
    .importUser-title {
        color: rgba(80, 80, 80, 1);
        font-size: 20px;
        text-align: left;
        font-weight: normal;
        padding: 30px 30px 20px 30px;
        margin: 0 15px;
        border-bottom: 1px #e8e8e8 solid;
    }
    .importUser-row{
        padding: 30px 45px 0 45px ;
        h3{
            color: rgba(80, 80, 80, 1);
            font-size: 16px;
            font-weight: normal;
        }
        p{
            color: rgba(80, 80, 80, 1);
            font-size: 14px;
            text-indent: 1em;
        }
        ul{
            list-style-type: decimal;
            color: rgba(128, 128, 128, 1);
            font-size: 14px;
        }
    }
    .importUser-btn{
        padding: 45px;
        button{
            width: 105px;
        }
    }
    .error-page{
        padding: 30px 45px;
    }
</style>